package cn.xhh.dailyreview.client.utils;

import cn.xhh.dailyreview.client.DailyReview;
import cn.xhh.dailyreview.client.utils.Result.Status;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class MsgCallback implements AsyncCallback<Result> {
	
	private DailyReview dailyReview;
	
	private boolean clearDone = false;

	public MsgCallback() {
	}
	
	public MsgCallback(DailyReview dailyReview) {
		this.dailyReview = dailyReview;
	}
	
	protected void clearLoading() {
		if (clearDone) return;
		
		if (dailyReview != null)
			dailyReview.hideInfo();
		
		clearDone = true;
	}

	/**
	 * First hide the info panel if dailyReview is given.<br/>
	 * Then show alerting for RPC call failure.<br/>
	 * @see com.google.gwt.user.client.rpc.AsyncCallback#onFailure(java.lang.Throwable)
	 */
	@Override
	public void onFailure(Throwable caught) {
		clearLoading();
		doFailure(caught);
	}
	
	public static void doFailure(Throwable caught) {
		GWT.log("RPC onFailure", caught);
		ClientUtil.alert(DailyReview.constants.errRpcFailure());
	}

	/**
	 * First hide the info panel if dailyReview is given.<br/>
	 * Then show alerting/info for the following cases:<br/>
	 * <code>result</code> is <code>null</code>, 
	 * or <code>result</code>.<code>status</code> is<br/>
	 * <code>ERR_SERVER</code>, <code>SUCCESS</code> or <code>FAILURE</code>.
	 * @see com.google.gwt.user.client.rpc.AsyncCallback#onSuccess(java.lang.Object)
	 */
	@Override
	public void onSuccess(Result result) {
		clearLoading();
		if (result==null || Status.ERR_SERVER==result.status)
			ClientUtil.alert(DailyReview.constants.errRpcFailure());
		else if (Status.SUCCESS == result.status)
			ClientUtil.info(DailyReview.constants.operationSucceeded());
		else if (Status.FAILURE == result.status)
			ClientUtil.info(DailyReview.constants.operationFailed());
	}

}
